from rest_framework import generics, status, mixins
from rest_framework.permissions import IsAuthenticated

from Group.models import Team, TeamMemberShip, TeamDetail
from Group.permission import IsTeamAdminOrCreator
from Group.serializers import TeamListSerializer, TeamMemberShipSerializer, TeamMemberShipApprovalSerializer, \
    TeamJoinRequestSerializer
from Person.authenticate import MyJSONWebTokenAuthentication
from Utils.BasePageNumberPagination import MyBasePageNumberPagination
from Utils.BaseResponse import BaseResponse


# Create your views here.

class TeamListGenericView(mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView):
    queryset = Team.objects.all()
    serializer_class = TeamListSerializer
    authentication_classes = [MyJSONWebTokenAuthentication]  # 登录认证
    permission_classes = [IsAuthenticated]
    pagination_class = MyBasePageNumberPagination  # 使用分页器
    ordering_fields = ['id', 'name', 'total_members', 'create_time']

    def get_queryset(self):
        user = self.request.user
        queryset = Team.objects.filter(is_delete=False)

        # 获取查询参数
        query_type = self.request.query_params.get('type')

        if query_type == 'joined':
            queryset = queryset.filter(team_detail__members=user)
        elif query_type == 'created':
            queryset = queryset.filter(creator=user)
        else:
            # 获取所有公开的团队
            public_teams = Team.objects.filter(team_type=1, is_delete=False)
            # 获取用户已加入的团队
            joined_teams = Team.objects.filter(team_detail__members=user, is_delete=False)
            # 使用 union 合并两个查询集，去重
            queryset = public_teams.union(joined_teams)

        return queryset

    def filter_queryset(self, queryset):
        queryset = super().filter_queryset(queryset)

        sort_field = self.request.query_params.get('sortField')
        sort_order = self.request.query_params.get('sortOrder')

        if sort_field and sort_order:
            if sort_field == 'createTime':
                sort_field = 'create_time'
            if sort_field == 'memberCount':
                # 手动处理 memberCount 排序
                reverse = (sort_order == 'descend')
                queryset = sorted(queryset, key=lambda x: x.total_members, reverse=reverse)
            else:
                if sort_order == 'descend':
                    sort_field = '-' + sort_field
                queryset = queryset.order_by(sort_field)

        return queryset

    def get(self, request, *args, **kwargs):
        res = super().list(request, *args, **kwargs)
        if res.status_code == 200:
            return BaseResponse(data={"list": res.data}, status=status.HTTP_200_OK).success()
        return BaseResponse(data=res.data, status=status.HTTP_400_BAD_REQUEST).fail()

    def perform_create(self, serializer):
        # 将当前请求的用户作为创建者传递给 serializer.save() 方法
        serializer.save(creator=self.request.user)

    def post(self, request, *args, **kwargs):
        response = super().create(request, *args, **kwargs)
        if response.status_code == 201:
            return BaseResponse(response.data,
                                status=status.HTTP_201_CREATED).success()
        return BaseResponse(data=response.data, status=status.HTTP_400_BAD_REQUEST).fail()


class ApplyToTeamView(generics.CreateAPIView):
    serializer_class = TeamMemberShipSerializer
    authentication_classes = [MyJSONWebTokenAuthentication]  # 登录认证
    permission_classes = [IsAuthenticated]

    def perform_create(self, serializer):
        team = serializer.validated_data['team']
        person = self.request.users
        serializer.save(person=person, is_active=False)

    def create(self, request, *args, **kwargs):
        response = super().create(request, *args, **kwargs)
        if response.status_code == 201:
            return BaseResponse({"detail": "Application submitted successfully.", "application": response.data},
                                status=status.HTTP_201_CREATED).success()
        return BaseResponse(data=response.data, status=status.HTTP_400_BAD_REQUEST).fail()


class ApproveTeamMemberView(generics.UpdateAPIView):
    serializer_class = TeamMemberShipApprovalSerializer
    authentication_classes = [MyJSONWebTokenAuthentication]  # 登录认证
    permission_classes = [IsAuthenticated, IsTeamAdminOrCreator]
    queryset = TeamMemberShip.objects.all()

    def update(self, request, *args, **kwargs):
        try:
            self.get_object()
        except TeamMemberShip.DoesNotExist:
            return BaseResponse(data={"detail": "Member does not exist."}, status=status.HTTP_404_NOT_FOUND).fail()
        response = super().update(request, *args, **kwargs)
        return BaseResponse({"detail": "Member approval status updated successfully.", "member": response.data},
                            status=status.HTTP_200_OK).success()


class TeamMembersAndRequestsView(generics.RetrieveAPIView):
    authentication_classes = [MyJSONWebTokenAuthentication]  # 登录认证
    permission_classes = [IsAuthenticated, IsTeamAdminOrCreator]

    def get(self, request, *args, **kwargs):
        team_id = kwargs.get('pk')
        try:
            team_detail = TeamDetail.objects.get(id=team_id)
        except TeamDetail.DoesNotExist:
            return BaseResponse({"detail": "Team not found."}, status=status.HTTP_404_NOT_FOUND).fail()

        members = TeamMemberShip.objects.filter(team=team_detail, is_active=True)
        members_serializer = TeamMemberShipSerializer(members, many=True)

        join_requests = TeamMemberShip.objects.filter(team=team_detail, is_active=False, is_quit=False)
        join_requests_serializer = TeamJoinRequestSerializer(join_requests, many=True)

        return BaseResponse({"members": members_serializer.data, "join_requests": join_requests_serializer.data},
                            status=status.HTTP_200_OK).success()
